import * as actionTypes from '../constants/index';
import { sleep } from '../until'
import axios from 'axios'
export const loginSuccess = (redirectTo) => {
  return {redirectTo,type:actionTypes.LOGIN}
}
export const errorMsg = (msg) => {
  return {msg,type:actionTypes.ERROR_MSG}
}
export const logout = () => {
  return {type:actionTypes.LOGOUT}
}
export const loadData = (data) => {
  return {type:actionTypes.LOAD_DATA,payload:data}
}
export const clearMsg = () => {
  return {type:actionTypes.CLEAR_MSG}
}
export const login = ({account,password})=>{
  if(!account||!password){
    return errorMsg('用户名密码必须输入')
  }
  return async dispatch=>{
    let res = await axios.post('vrv-monitor-platform-web/login',{
      account,
      password
    })
    if(res.data.success){
      localStorage.setItem('selectedValue','0')
      let redirectTo = '/home'
      dispatch(loginSuccess(redirectTo))
    }else{
      dispatch(errorMsg(res.data.message))
    }
  }
}

async function err(d,m){
  d(errorMsg(m))
  await sleep(600)
  d(clearMsg())
}
export const updateUserInfo = ({email,phone,userName}) => {
  return async dispatch => {
    let res = await axios.post('vrv-monitor-platform-web/user/update/userInfo',{email,phone,userName})
    if(res.data.success){
      dispatch(loadData({email,phone,userName,edit:true}))
      err(dispatch,'保存成功')
    }else{
      err(dispatch,res.data.message)
    }
  }
}

export const getUserInfo = () => {
  return async dispatch => {
    let res = await axios.get('/vrv-monitor-platform-web/user/read/userInfo')
    // let res1 = await axios.get('vrv-monitor-platform-web/industry/list')
    // let nature = res1&&res1.data.data.filter( d => d.id == parseInt(res.data.data.industryInvolved))[0].industryName
    if(res.data.success){
      let data ={...res.data.data}
      dispatch(loadData(data))
    }
  }
}